<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <title>Title</title>
</head>
<body>
<h1>测试页面停留时间</h1>
</body>
<script>
    var second = 0;
    window.setInterval(function () {
        second ++;
    }, 1000);
    var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
    $.cookie('tjRefer', getReferrer() ,{expires:1,path:'/'});

    window.onbeforeunload = function() {
        if ($.cookie('tjRefer') == '') {
            var tjT = eval('(' + localStorage.getItem("jsArr") + ')');
            if (tjT) {
                tjT[tjT.length - 1].time += second;
                var jsArr = JSON.stringify(tjT);
                localStorage.setItem("jsArr", jsArr);
            }
        } else {
            var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
            var dataArr = {
                'url': location.href,
                'time': second,
                'refer': getReferrer(),
                'timeIn': Date.parse(new Date()),
                'timeOut': Date.parse(new Date()) + (second * 1000)
            };
            tjArr = eval('(' + tjArr + ')');
            tjArr.push(dataArr);
            tjArr = JSON.stringify(tjArr);
            localStorage.setItem("jsArr", tjArr);
        }
    };

    function getReferrer() {
        var referrer = '';
        try {
            referrer = window.top.document.referrer;
        } catch(e) {
            if(window.parent) {
                try {
                    referrer = window.parent.document.referrer;
                } catch(e2) {
                    referrer = '';
                }
            }
        }
        if(referrer === '') {
            referrer = document.referrer;
        }
        return referrer;
    }
</script>
</html>